package com.app.mingluxing.location;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.WhiteListAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.ResultBaseBean;
import com.app.mingluxing.bean.WhiteListResult;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.DensityUtil;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 手环白名单页面
 * Created by Aaron on 15/8/5.
 */
public class WhiteListActivity extends BaseActivity {

    private EditText et_tel;
    private EditText et_nickname;
    private TextView tv_create;
    private TextView tv_cancle;
    private Dialog whiteListDialog;
    private WhiteListAdapter adapter;
    //    private String watchId;
//    boolean isDelet;
//    private String sn;
    public List<WhiteListResult.White> list = new ArrayList<WhiteListResult.White>();
    private WhiteListResult.White remove;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_safe_area);
//        watchId=getIntent().getStringExtra("watchId");
//        sn=getIntent().getStringExtra("sn");

        initWidget();
//        getWhiteList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWhiteList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
//        ImageView iv_right = (ImageView) findViewById(R.id.iv_right);
//        iv_right.setImageResource(R.drawable.icon_delete_white_list);

        ImageView iv_add_fence = (ImageView) findViewById(R.id.iv_add_fence);

        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.watch_white_list));

        TextView tv_add = (TextView) findViewById(R.id.tv_add);
        tv_add.setText(getResources().getString(R.string.add_safe_phone));

        SwipeMenuListView lv_safe_area = (SwipeMenuListView) findViewById(R.id.lv_safe_area);

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
//                // create "open" item
//                SwipeMenuItem openItem = new SwipeMenuItem(
//                        getApplicationContext());
//                // set item background
//                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
//                        0xCE)));
//                // set item width
//                openItem.setWidth(DensityUtil.dip2px(SafeAreaActivity.this, 90));
//                // set item title
//                openItem.setTitle("Open");
//                // set item title fontsize
//                openItem.setTitleSize(18);
//                // set item title font color
//                openItem.setTitleColor(Color.WHITE);
//                // add to menu
//                menu.addMenuItem(openItem);

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(DensityUtil.dip2px(WhiteListActivity.this, 90));

                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);

            }
        };

        adapter = new WhiteListAdapter(this, list);
        lv_safe_area.setAdapter(adapter);

        // set creator
        lv_safe_area.setMenuCreator(creator);

        lv_safe_area.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        // 删除白名单
                        if (list != null && list.size() > 0) {
                            remove = list.remove(position);
                            updateWhiteList(list, 1);
                        }
                        break;
//                    case 1:
//                        // open
//
//                        LogUtil.e("TAG", "item=====1");
//
//                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });

        iv_left.setOnClickListener(this);
        iv_add_fence.setOnClickListener(this);
//        iv_right.setOnClickListener(this);

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

//            case R.id.iv_right://删除白名单按钮
//
//                if (isDelete) {
//                    //当前是删除模式, 切换到非删除模式
//                    adapter.setStyle(2);
//                    adapter.notifyDataSetChanged();
//                    isDelete = false;
//
//                }else {
//                    //当前是删除模式,切换到非删除模式
//                    adapter.setStyle(1);
//                    adapter.notifyDataSetChanged();
//                    isDelete = true;
//                }
//
//                break;

            case R.id.iv_add_fence://添加白名单

                addWhiteList();

                break;
            case R.id.tv_create://创建白名单

                createWhiteList();

                break;
            case R.id.tv_cancle://取消

                if (whiteListDialog != null && whiteListDialog.isShowing())
                    whiteListDialog.dismiss();

                break;

        }

    }

    /**
     * 创建白名单
     */
    private void createWhiteList() {

        if (!CommonUtils.isPhone(et_tel.getText().toString().trim())) {

            showToast("手机号码格式不正确");
            return;
        }

        if (CommonUtils.isNull(et_nickname.getText().toString().trim())) {
            showToast("请输入昵称");
            return;
        }

        if (CommonUtils.isPhone(et_tel.getText().toString().trim())) {

            String name = et_nickname.getText().toString().trim();
            String phoneNum = et_tel.getText().toString().trim();
            WhiteListResult.White white = new WhiteListResult().new White();
            white.name = name;
            white.phoneNum = phoneNum;
            list.add(white);

            updateWhiteList(list, 0);

        } else {
            showToast("请输入正确的电话号码");
            return;
        }
    }

    /**
     * 更新白名单
     *
     * @param whiteList
     * @param style     是删除还是添加 0 是创建 1 是删除
     */
    private void updateWhiteList(List<WhiteListResult.White> whiteList, final int style) {

        WhiteListResult whiteListResult = new WhiteListResult();
        whiteListResult.token = sp.getString(Constant.TOKEN, "");
        whiteListResult.id = sp.getString(Constant.CURRENTCHILDID, "");
        whiteListResult.whiteList = whiteList;
//        String requestStr=JSONObject.toJSONString(whiteListResult);

        HttpUtil.setPostRequest("提交中...", this, Constant.WEB_ROOT + Constant.UPDATEWHITELIST,
                JSONObject.toJSONString(whiteListResult), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);
                            if (resultBaseBean.code == Constant.STATUS_SUCCESS) {

                                //更新成功
                                if (whiteListDialog != null && whiteListDialog.isShowing())
                                    whiteListDialog.dismiss();
                                showToast("成功");
//                        getWhiteList();

                            } else {
                                showToast(Constant.showErrorMsg(resultBaseBean.code, getApplication()));
                                //更新失败
                                switch (style) {
                                    case 0: //创建失败
                                        //删除集合中最后一个元素 (即需要添加的白名单)

                                        if (list != null && list.size() > 0) {
                                            list.remove(list.size() - 1);
                                        }

                                        break;

                                    case 1://删除白名单失败

                                        if (remove != null && list != null) {
                                            list.add(remove);
                                        }

                                        break;
                                }

                            }

                            adapter.setData(list);
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);
    }

    /**
     * 添加手环白名单
     */
    private void addWhiteList() {

        whiteListDialog = new Dialog(this, R.style.no_title);
// new Dialog();
        whiteListDialog.setCancelable(true);
        whiteListDialog.setCanceledOnTouchOutside(true);
        whiteListDialog.show();
        whiteListDialog.setContentView(R.layout.dialog_add_white_list);
//        whiteListDialog.getWindow().setContentView(R.layout.dialog_add_white_list);
//        whiteListDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        et_tel = (EditText) whiteListDialog.findViewById(R.id.et_tel);
        et_nickname = (EditText) whiteListDialog.findViewById(R.id.et_nickname);
        tv_create = (TextView) whiteListDialog.findViewById(R.id.tv_create);
        tv_cancle = (TextView) whiteListDialog.findViewById(R.id.tv_cancle);

        tv_create.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

    }

    /**
     * 获取白名单列表
     */
    private void getWhiteList() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.GETWHITELIST, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            WhiteListResult whiteListResult = JSONObject.parseObject(str, WhiteListResult.class);
                            if (whiteListResult.code == Constant.STATUS_SUCCESS) {

                                if (whiteListResult.whiteList != null && whiteListResult.whiteList.size() > 0) {
                                    list.clear();
                                    list = whiteListResult.whiteList;
                                    adapter.setData(list);
                                    adapter.notifyDataSetChanged();
                                }

                            } else {
                                showToast(Constant.showErrorMsg(whiteListResult.code, getApplication()));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);
    }

}
